/**
 * Copyright (c) 2025 myons Inc. All rights reserved.
 */
package cn.zmwh.common.core.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.zmwh.common.core.utils.IdGenerator;
import cn.zmwh.common.core.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.info.BuildProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @describe: 初始化、
 * @author: dmzmwh 、
 * @time: 2025-07-18 17:13 、
 */
@Slf4j
@Configuration
public class InitConfig implements ApplicationRunner {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private Environment env;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        idInit();//分布式id初始化服务id和数据分区id
    }

    public void idInit() {
        String key = env.getProperty("spring.application.name") + ":id";
        long incr = redisUtils.incr(key, 1);
        // 从配置文件读取 workerId 和 dataCenterId
        long dataCenterId = 0;
        if (incr > 30) {
            log.error("服务器ID不能大于30");
            dataCenterId = RandomUtil.randomInt(0, 32);
            redisUtils.del(key);
        }
        Snowflake snowflake = IdUtil.getSnowflake(incr, dataCenterId);
        IdGenerator.init(snowflake);
    }
}

